import { observable, action, useStrict, computed, asMap, toJS } from 'mobx';
import BaseStore from './BaseStore';
import * as API_REQ from '../apis/form';
import * as mobx from 'mobx';
import base from '../util/base';
import { _ } from '../util/pcPublic';
import { getLabel } from '../util/common';

const initState = {
    baseParam: {},
    cardid: "",
    counts: {},
    dataMap: observable.map ? observable.map({}) : asMap({}),
    paramMap: observable.map ? observable.map({}) : asMap({}),
    spreadMap: observable.map ? observable.map({}) : asMap({}),
}

export class StatusStore extends BaseStore{

    baseParam;
    @observable cardid;
    @observable counts;
    @observable dataMap;
    paramMap;
    @observable spreadMap;
    
    constructor(){
        super();
        this.changeState(initState);
        this.setBaseParam = this.setBaseParam.bind(this);
        this.switchCard = this.switchCard.bind(this);
        this.loadCounts = this.loadCounts.bind(this);
        this.loadData = this.loadData.bind(this);
        this.controlSpreadDatas = this.controlSpreadDatas.bind(this);
    }

    @action
    setBaseParam(param={}){
        this.baseParam = param;
    }

    @action('切换卡片类型')
    switchCard(cardid){
        this.cardid = cardid;
        if(!this.dataMap.has(cardid))
            this.loadData(true);
    }

    @action('加载计数信息')
    loadCounts(){
        API_REQ.getWfStatusCount(this.baseParam).then(data => {
            this.counts = data;
            this.nodeOptions = data.selectNodeOptions;
        });
    }

    @action('加载流程状态数据')
    loadData(isfirst){
		let params = {...this.baseParam, ...{desremark:this.cardid, isfirst:isfirst, pageSize:30}};
		if(!isfirst)
            params["parameter"] = JSON.stringify(this.paramMap.get(this.cardid));
        base.wfGlobalStore.setLoading(true);
		API_REQ.getWfStatus(params).then(data => {
            base.wfGlobalStore.setLoading(false);
            const { datas,parameter } = data;
            let newData = this.dataMap.has(this.cardid) ? _.cloneDeep(mobx.toJS(this.dataMap.get(this.cardid))) : {};
            let appendSpread = [];
            !_.isEmpty(datas) && _.forIn(datas, (nodeData,key) =>{
                if(key in newData){     //同节点追加数据
                    newData[key].list = _.concat(newData[key].list || [], nodeData.list || [])
                }else{
                    newData[key] = nodeData;
                    appendSpread.push(key);
                }
            });
            this.dataMap.set(this.cardid, newData);
            this.paramMap.set(this.cardid, parameter);
            //默认展开节点信息
            const oldSpreadDatas = this.spreadMap.has(this.cardid) ? mobx.toJS(this.spreadMap.get(this.cardid)) : [];
            this.controlSpreadDatas(oldSpreadDatas.concat(appendSpread));
        });
    }

    @action('控制节点组伸缩')
    controlSpreadDatas(datas){
        this.spreadMap.set(this.cardid, datas);
    }

}